﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using System.Configuration;
using UCHENG.FILEHASH.UTILS;
using DevExpress.XtraSplashScreen;
using System.Diagnostics;
using UCHENG.FILEHASH.UTILS.ADB;

namespace UCHENG.FILEHASH
{
    public partial class frmMain : XtraForm
    {
        private const string PLAYERCODE = "PlayerCode";
        private const string PLAYERVERSION = "PlayerVersion";
        private const string PPTPLAYERPATH = "101PPTPlayer";
        private const string PHONEPLAYERPATH = "PhonePlayer";

        private const string PPTPLAYERPATHDIR = "101Player";
        private const string DEVELOPERDIST = "DeveloperDist";
        private string[] devs;

        public string Tab2ConfigPath
        {
            get
            {
                return System.Environment.CurrentDirectory + "\\" + "tab2_config.json";
            }
        }

        public string Tab1ConfigPath
        {
            get
            {
                return System.Environment.CurrentDirectory + "\\" + "tab1_config.json";
            }
        }

        public string DeviceId { get; set; }

        /// <summary>
        /// 是否连接手机成功
        /// </summary>
        public bool IsSuccess { get; set; }


        public frmMain()
        {
            InitializeComponent();

            initPage();
        }

        private void initPage()
        {
            var playerCode = ConfigurationManager.AppSettings[PLAYERCODE];
            var playerVersion = ConfigurationManager.AppSettings[PLAYERVERSION];
            var pcPlayerPath = ConfigurationManager.AppSettings[PPTPLAYERPATH];
            var phonePlayerPath = ConfigurationManager.AppSettings[PHONEPLAYERPATH];

            var pcPlayerDir = ConfigurationManager.AppSettings[PPTPLAYERPATHDIR];
            var devloperDist = ConfigurationManager.AppSettings[DEVELOPERDIST];

            txtCode.Text = playerCode;
            txtVersion.Text = playerVersion;
            txtPath.Text = pcPlayerPath;
            txtPhonePath.Text = phonePlayerPath;
            txtPhonePath1.Text = phonePlayerPath;

            txtPlayerDir.Text = pcPlayerDir;
            txtDist.Text = devloperDist;


            if (File.Exists(Tab1ConfigPath))
            {
                string configText = File.ReadAllText(Tab1ConfigPath);
                string[] configs = configText.Split('|');
                txtCode.Text = configs[0];
                txtVersion.Text = configs[1];
                txtPath.Text = configs[2];
                txtPhonePath.Text = configs[3];
                try
                {
                    chkPlayer.Checked = Convert.ToBoolean(Convert.ToInt32(configs[4]));
                }
                catch
                {
                    chkPlayer.Checked = false;
                }

                try
                {
                    chkPhone.Checked = Convert.ToBoolean(Convert.ToInt32(configs[5]));
                }
                catch
                {
                    chkPhone.Checked = false;
                }

            }

            if (File.Exists(Tab2ConfigPath))
            {
                string configText = File.ReadAllText(Tab2ConfigPath);
                string[] configs = configText.Split('|');
                txtSolution.Text = configs[0];
                meCodes.Text = configs[1];
                txtDist.Text = configs[2];
                txtPlayerDir.Text = configs[3];
                txtPhonePath1.Text = configs[4];
            }

            startAdbServer();
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {

            DevExpress.XtraSplashScreen.SplashScreenManager.ShowForm(typeof(frmWaiting));

            DownloadService downloadService = new DownloadService();
            downloadService.TeacherPlayerDownLoadCompleteEventHandler += DownloadService_TeacherPlayerDownLoadCompleteEventHandler;
            downloadService.StudentPlayerDownLoadCompleteEventHandler += DownloadService_StudentPlayerDownLoadCompleteEventHandler;
            downloadService.Excute(new PlayerVo()
            {
                DeviceId = DeviceId,
                IsReplace = chkPlayer.Checked,
                IsReplacePhone = chkPhone.Checked,
                PhonePlayerPath = txtPhonePath.Text,
                PlayerCode = txtCode.Text,
                PlayerPath = txtPath.Text,
                PlayerVersion = txtVersion.Text
            });


            File.WriteAllText(Tab1ConfigPath, txtCode.Text + "|" + txtVersion.Text + "|" + txtPath.Text + "|" + txtPhonePath.Text + "|" + (chkPlayer.Checked == true ? "1" : "0") + "|" + (chkPhone.Checked == true ? "1" : "0"));

            DevExpress.XtraSplashScreen.SplashScreenManager.CloseForm();

            DevExpress.XtraEditors.XtraMessageBox.Show("替换完成", "提示");
        }

        private void DownloadService_TeacherPlayerDownLoadCompleteEventHandler(object sender, EventArgs e)
        {

        }

        private void DownloadService_StudentPlayerDownLoadCompleteEventHandler(object sender, EventArgs e)
        {

        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //自动清理adb进程	
            try
            {
                var processess = Process.GetProcessesByName("adb");
                foreach (var process in processess)
                    if (process.StartInfo.FileName.Contains(Application.StartupPath))
                        process.Kill();
            }
            catch
            {
                //ignore all
            }
        }

        private void startAdbServer()
        {
            string message = string.Empty;
            //启动服务
            if (!AdbHelper.StartServer(Application.StartupPath))
            {
                message = "服务启动失败！";
                lblMessage.Text = message;
                lblMessage.ForeColor = Color.Red;
                lblMessage1.Text = message;
                lblMessage1.ForeColor = Color.Red;
                IsSuccess = false;
                return;
            }

            //获取设备列表
            devs = AdbHelper.GetDevices();
            if (devs.Length == 0)
            {
                message = "没有连接设备！";
                lblMessage.Text = message;
                lblMessage.ForeColor = Color.Red;
                lblMessage1.Text = message;
                lblMessage1.ForeColor = Color.Red;
                IsSuccess = false;
                return;
            }

            if (devs.Length > 0)
            {
                DeviceId = devs[0];
            }


            message = "成功连接设备！";
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = message;
            lblMessage1.ForeColor = Color.Green;
            lblMessage1.Text = message;
            IsSuccess = true;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            initPage();
        }



        private void btnFileReplace_Click(object sender, EventArgs e)
        {

            string solution = txtSolution.Text;

            string[] codes = meCodes.Text.Split(',');

            string phonePlayer = txtPhonePath1.Text;

            foreach (string code in codes)
            {
                string filePath = string.Format(txtDist.Text, solution, code);

                if (!FileService.Exists(filePath))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("文件不存在, 编码：" + code, "提示");
                    return;
                }

                string dirPath = string.Format(txtPlayerDir.Text, code);
                if (!FileService.DirExists(dirPath))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("PcPlayer目录不存在", "提示");
                    return;
                }


                string fileName = Path.GetFileName(filePath);

                File.Copy(filePath, dirPath + "\\" + fileName, true);

                if (File.Exists(Tab2ConfigPath))
                {
                    File.Delete(Tab2ConfigPath);
                }

                File.WriteAllText(Tab2ConfigPath, solution + "|" + code + "|" + txtDist.Text + "|" + txtPlayerDir.Text + "|" + txtPhonePath1.Text);


                string phoneDirPath = string.Format(txtPhonePath1.Text, code);
                if (IsSuccess)
                {
                    AdbHelper.CopyFileToDevice(DeviceId, filePath, phoneDirPath);
                }

            }

            DevExpress.XtraEditors.XtraMessageBox.Show("替换完成", "提示");
        }

        private void tabPane1_SelectedPageChanged(object sender, DevExpress.XtraBars.Navigation.SelectedPageChangedEventArgs e)
        {
            if(tabPane1.SelectedPageIndex == 2)
            {
                frmLogin frmLogin = new frmLogin();
                if (frmLogin.ShowDialog() == DialogResult.OK)
                {

                }
            }
        }
    }
}
